/**
* Copyright (c) 2015 UNI-TREND Co., Ltd.
* All rights reserved.  
*  
* @file        log.cpp
* @brief      impl Clog
* @version     1.0 
* @author      
* @Email       
* @date        2015-11-13
*/
#include "Log.h"
#include "Assistant.h"
#include <xutility>
#include <time.h>
#include <iostream>
using namespace std;

const int CLog::MAX_LOG_LENGTH = 1024;

char* CLog::m_logger = (char*)malloc(sizeof(char) * CLog::MAX_LOG_LENGTH);
int CLog::m_logBeginFrom = 0;
int CLog::m_logLength = 0;

BOOL CLog::error(string warn, LOG_DETAILED type)
{    
    assert(type <= LOG_FULL);
    string str = "";
    if(type == LOG_LESS_10BYTE)
    {
        str = "E," + warn.substr(0, 10) + "\n";
    }
    else if(type == LOG_2END)
    {
        str = "ERR," + warn + "\n";
    }
    
    return record(str);
}

BOOL CLog::warning(string warn, LOG_DETAILED type)
{    
    assert(type <= LOG_FULL);
    string str = "";
    if(type == LOG_LESS_10BYTE)
    {
        str = "W," + warn.substr(0, 10) + "\n";
    }
    else if(type == LOG_2END)
    {
        str = "WARN," + warn + "\n";
    }
    
    return record(str);
}

BOOL CLog::info(string warn, LOG_DETAILED type)
{    
    assert(type <= LOG_FULL);
    string str = "";
    if(type == LOG_LESS_10BYTE)
    {
        str = "I," + warn.substr(0, 10) + "\n";
    }
    else if(type == LOG_2END)
    {
        str = "Info," + warn + "\n";
    }
    else if(type == LOG_TIK_TOK)
    {
        char tt[50] = {0};
        sprintf(tt, "%d\n", clock());
        str = "TT," + warn + "," + string(tt);
    }
    
    return record(str);
}

BOOL CLog::record(string str)
{
    // debug-code
    cout<<"[LOG]"<<str;// 'str' already has a return code, by info/warning/error

    char* pLog = CLog::m_logger;
    for(int i=0; i<str.length(); i++)
    {
        // char by char
        pLog[CLog::m_logBeginFrom] = str.c_str()[i];
        // begin pos
        CLog::m_logBeginFrom = (CLog::m_logBeginFrom + 1) % CLog::MAX_LOG_LENGTH;
        // length
        CLog::m_logLength = min(CLog::MAX_LOG_LENGTH, (CLog::m_logLength + 1));
    }
    return TRUE;
}

